<script lang="ts" setup>
import {onBeforeUnmount, ref} from "vue";
import {message} from "@/utils/ElmessasgeUtils";

let terminalSocket = ref()
const isConnecting = ref(false)
const messageList = ref<any[]>([])
const inputMessage = ref('')
const connectionStatus = ref('disconnected')

// 连接到Websocket 服务器
function connectToServer() {
  if (!terminalSocket.value || (terminalSocket.value && terminalSocket.value.readyState > 1)) {
    terminalSocket.value = new WebSocket('ws://' + location.host + '/WebShell/socket/webShell-connect');
    connectionStatus.value = 'connecting';
  }

  terminalSocket.value.onopen = () => {
    message("WebSocket Connected!")
    isConnecting.value = true
    connectionStatus.value = 'connected';
  }

  terminalSocket.value.onmessage = (msg: any) => {
    messageList.value.push({
      type: 'received',
      content: msg.data
    });
    // 自动滚动到底部
    setTimeout(() => {
      const messageContainer = document.getElementById('message-container');
      if (messageContainer) {
        messageContainer.scrollTop = messageContainer.scrollHeight;
      }
    }, 100);
  }

  terminalSocket.value.onclose = () => {
    message("websocket连接关闭", 'error');
    isConnecting.value = false
    connectionStatus.value = 'disconnected';

    terminalSocket.value && terminalSocket.value.close()
  }
  terminalSocket.value.onerror = (error: any) => {
    message("websocket连接出现错误", 'error');
    console.log(error);
    console.log(JSON.stringify(error));
    isConnecting.value = false
    connectionStatus.value = 'error';

    terminalSocket.value && terminalSocket.value.close()
  }

}

// 发送消息到WebSocket 服务器
function sendMessageToWSServer(msg: any) {
  if (isConnecting.value) {
    terminalSocket.value.send(
        JSON.stringify(msg)
    )
    // 添加发送的消息到列表
    messageList.value.push({
      type: 'sent',
      content: msg.command
    });
    inputMessage.value = '';
    // 自动滚动到底部
    setTimeout(() => {
      const messageContainer = document.getElementById('message-container');
      if (messageContainer) {
        messageContainer.scrollTop = messageContainer.scrollHeight;
      }
    }, 100);
  } else {
    message("WebSocket未连接，请先连接服务器", 'warning');
  }
}

// 处理发送消息
const handleSendMessage = () => {
  if (inputMessage.value.trim()) {
    sendMessageToWSServer({
      operate: 'commonMessage',
      command: inputMessage.value
    });
  }
}

// 处理回车键发送
const handleKeyPress = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    handleSendMessage();
  }
}

// 断开连接
const disconnect = () => {
  if (terminalSocket.value) {
    terminalSocket.value.close();
    terminalSocket.value = null;
    isConnecting.value = false;
    connectionStatus.value = 'disconnected';
    message("WebSocket已断开连接");
  }
}


// 解除挂载前 关闭连接
onBeforeUnmount(() => {
  terminalSocket.value && terminalSocket.value.close()

})

</script>

<template>
  <div class="websocket-client-container">
    <!-- 标题和连接控制区域 -->
    <div class="header-section">
      <h2 class="client-title">WebSocket 客户端</h2>
      <div class="connection-controls">
        <span :class="connectionStatus" class="status-indicator">{{ connectionStatus }}</span>
        <button
            :disabled="isConnecting"
            class="connect-btn"
            @click="connectToServer"
        >
          {{ isConnecting ? '连接中...' : '连接服务器' }}
        </button>
        <button
            :disabled="!isConnecting"
            class="disconnect-btn"
            @click="disconnect"
        >
          断开连接
        </button>
      </div>
    </div>

    <!-- 消息显示区域 -->
    <div class="message-display-container">
      <div id="message-container" class="message-container">
        <div v-if="messageList.length === 0" class="empty-message">
          暂无消息，请先连接服务器
        </div>
        <div
            v-for="(msg, index) in messageList"
            :key="index"
            :class="['message-item', msg.type]"
        >
          <!--          <div class="message-type">{{ msg.type === 'sent' ? '发送' : '接收' }}</div>-->
          <div class="message-content">{{ JSON.stringify(msg.content, null, 2) }}</div>
          <div class="message-time">{{ new Date().toLocaleTimeString() }}</div>
        </div>
      </div>
    </div>

    <!-- 消息输入区域 -->
    <div class="input-section">
      <textarea
          v-model="inputMessage"
          class="message-input"
          placeholder="请输入消息内容...\n(按Enter发送，Shift+Enter换行)"
          rows="3"
          @keydown="handleKeyPress"
      ></textarea>
      <button
          :disabled="!inputMessage.trim() || !isConnecting"
          class="send-btn"
          @click="handleSendMessage"
      >
        发送消息
      </button>
    </div>
  </div>
</template>

<style scoped>
.websocket-client-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8e8e8;
}

.client-title {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.connection-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.status-indicator {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.status-indicator.connected {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-indicator.connecting {
  background-color: #fffbe6;
  color: #faad14;
  border: 1px solid #ffe58f;
}

.status-indicator.disconnected {
  background-color: #fff2f0;
  color: #f5222d;
  border: 1px solid #ffccc7;
}

.status-indicator.error {
  background-color: #fff2f0;
  color: #f5222d;
  border: 1px solid #ffccc7;
}

.connect-btn, .disconnect-btn, .send-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.connect-btn {
  background-color: #1890ff;
  color: white;
}

.connect-btn:hover:not(:disabled) {
  background-color: #40a9ff;
}

.connect-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.disconnect-btn {
  background-color: #f5222d;
  color: white;
}

.disconnect-btn:hover:not(:disabled) {
  background-color: #ff4d4f;
}

.disconnect-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.message-display-container {
  height: 400px;
  margin-bottom: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}

.message-container {
  height: 100%;
  padding: 15px;
  overflow-y: auto;
  background-color: #fafafa;
}

.empty-message {
  text-align: center;
  color: #999;
  margin-top: 150px;
  font-size: 14px;
}

.message-item {
  margin-bottom: 15px;
  padding: 10px 15px;
  border-radius: 8px;
  max-width: 80%;
  word-wrap: break-word;
  position: relative;
}

.message-item.sent {
  background-color: #e6f7ff;
  margin-left: auto;
  border: 1px solid #bae7ff;
}

.message-item.received {
  background-color: #ffffff;
  margin-right: auto;
  border: 1px solid #d9d9d9;
}

.message-type {
  font-size: 12px;
  font-weight: 600;
  margin-bottom: 5px;
  color: #666;
}

.message-content {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  white-space: pre-wrap;
}

.message-time {
  font-size: 11px;
  color: #999;
  text-align: right;
  margin-top: 5px;
}

.input-section {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
  min-height: 60px;
  max-height: 120px;
  font-family: inherit;
}

.message-input:focus {
  outline: none;
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.send-btn {
  background-color: #52c41a;
  color: white;
  min-height: 40px;
}

.send-btn:hover:not(:disabled) {
  background-color: #73d13d;
}

.send-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

/* 滚动条样式 */
.message-container::-webkit-scrollbar {
  width: 6px;
}

.message-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.message-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.message-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>